//
//  ShopTabScrollView.m
//  TestPrj
//
//  Created by 朱铅峰 on 2020/6/22.
//  Copyright © 2020 Xing. All rights reserved.
//

#import "ShopTabScrollView.h"
#import "PartProductView.h"
#import "PartEvaluateView.h"
#import "PartMerchantView.h"
#import "MTShopSingleModel.h"
#import "MTShopDynamicItem.h"

/*f(x, d, c) = (x * d * c) / (d + c * x)
 where,
 x – distance from the edge
 c – constant (UIScrollView uses 0.55)
 d – dimension, either width or height*/

static CGFloat rubberBandDistance(CGFloat offset, CGFloat dimension) {
    const CGFloat constant = 0.55f;
    CGFloat result = (constant * fabs(offset) * dimension) / (dimension + constant * fabs(offset));
    // The algorithm expects a positive offset, so we have to negate the result if the offset was negative.
    return offset < 0.0f ? -result : result;
}

@interface ShopTabScrollView()<UIScrollViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic , strong) UIView *menuView;//菜单视图
@property (nonatomic , strong) UIView *menuLine;

@property (nonatomic , strong) UIScrollView *horizonScrollView;//横向水平滚动视图
@property (nonatomic , strong) PartProductView *productView;//商家列表主页,二级联动
@property (nonatomic , strong) PartMerchantView *merchantView;//商家视图
@property (nonatomic , strong) PartEvaluateView *evaluateView;//评价视图
@property (nonatomic , strong) UIScrollView *subTableView;//获取当前页面的子tableView.


proAssign NSInteger lastIndex;
proAssign NSInteger currentIndex;
proAssign BOOL isVertical;//是否是垂直滑动

//弹性和惯性动画
proStrong UIDynamicAnimator *animator;
proWeak   UIDynamicItemBehavior *decelerationBehavior;
proStrong MTShopDynamicItem *dynamicItem;
proWeak   UIAttachmentBehavior *springBehavior;

@end

@implementation ShopTabScrollView

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        self.delegate = self;
        self.scrollEnabled = NO;
        self.contentSize = CGSizeMake(self.width, self.height + [MTShopSingleModel sharedInstance].maxOffsetY);
        
        [self addViews];
    }
    return self;
}

- (void)addViews {
    
    //============================== 头部及菜单
    
    self.currentIndex = 1;
    self.lastIndex = 1;
    
    //1:顶部高度为_maxOffset_Y，背景透明，可以点击
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.width, [MTShopSingleModel sharedInstance].maxOffsetY)];
    topView.userInteractionEnabled = YES;
    [self addSubview:topView];
    
    //2:添加点击事件
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dropDownTap:)];
    [topView addGestureRecognizer:tap];
    
    //3:创建 商品,评价,商家
    UIView *menuView = [[UIView alloc]initWithFrame:CGRectMake(0, [MTShopSingleModel sharedInstance].maxOffsetY, self.width, 36)];
    menuView.backgroundColor = [UIColor whiteColor];
    [self addSubview:menuView];
    _menuView = menuView;
    
    //商品
    CGFloat button_W = self.width/3;
    UIButton *productBT = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [productBT setFrame:CGRectMake(0, 0, button_W, menuView.height)];
    [productBT setBackgroundColor:[UIColor whiteColor]];
    [productBT setTitle:@"商品" forState:UIControlStateNormal];
    [productBT setTitleColor:kColorBlack forState:UIControlStateNormal];
    productBT.tag = 1;
    [productBT addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    productBT.titleLabel.font = [UIFont systemFontOfSize:14];
    [menuView addSubview:productBT];
    
    //评价
    UIButton *evaluateBT = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [evaluateBT setFrame:CGRectMake(button_W, 0, button_W, menuView.height)];
    [evaluateBT setBackgroundColor:[UIColor whiteColor]];
    [evaluateBT setTitle:@"评价（3）" forState:UIControlStateNormal];
    [evaluateBT setTitleColor:kColorLightGray forState:UIControlStateNormal];
    evaluateBT.tag = 2;
    [evaluateBT addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    evaluateBT.titleLabel.font = [UIFont systemFontOfSize:14];
    [menuView addSubview:evaluateBT];
    
    //商家
    UIButton *merchantBT = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [merchantBT setFrame:CGRectMake(button_W*2, 0, button_W, menuView.height)];
    [merchantBT setBackgroundColor:[UIColor whiteColor]];
    [merchantBT setTitle:@"商家" forState:UIControlStateNormal];
    [merchantBT setTitleColor:kColorLightGray forState:UIControlStateNormal];
    merchantBT.tag = 3;
    [merchantBT addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    merchantBT.titleLabel.font = [UIFont systemFontOfSize:14];
    [menuView addSubview:merchantBT];

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, menuView.height-1, self.width, 1)];
    line.backgroundColor = kColorLineColor;
    [menuView addSubview:line];
    
    //4:可移动的底部滑竿
    self.menuLine = [[UILabel alloc]init];
    self.menuLine.frame = CGRectMake(productBT.center.x-10, menuView.height-2, 20, 2);
    self.menuLine.backgroundColor = [UIColor redColor];
    [menuView addSubview:self.menuLine];
    
    //============================== 横向滚动视图
    
    [self addSubview:self.horizonScrollView];
    [self.horizonScrollView addSubview:self.productView];
    [self.horizonScrollView addSubview:self.evaluateView];
    [self.horizonScrollView addSubview:self.merchantView];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureRecognizerAction:)];
    pan.delegate = self;
    [self addGestureRecognizer:pan];
    
    self.animator = [[UIDynamicAnimator alloc] initWithReferenceView:self];
    self.dynamicItem = [[MTShopDynamicItem alloc] init];
    
    self.subTableView = [self currentSubTableView];
}

#pragma mark - 控制事件

//下拉，显示店铺详情
- (void)dropDownTap:(UITapGestureRecognizer *)tap {
    
    //点击顶部，让整个滚动视图平移
    if ([self.scrollDelegate respondsToSelector:@selector(ShopTabScrollViewDropDown:)]) {
        //删除所有动力行为。
        [self removeBehaviors];
        [self.scrollDelegate ShopTabScrollViewDropDown:self];
    }
}

/// 菜单按钮事件
/// @param btn <#btn description#>
- (void)menuBtnClick:(UIButton *)btn {
    
    NSInteger tag = btn.tag;
    _currentIndex = tag;
    UIButton *lastBT = (UIButton *)[_menuView viewWithTag:_lastIndex];
    [lastBT setTitleColor:kColorLightGray forState:UIControlStateNormal];
    [btn setTitleColor:kColorBlack forState:UIControlStateNormal];

    _lastIndex = tag;
    [self removeBehaviors];
    
    [self.horizonScrollView setContentOffset:CGPointMake((_lastIndex-1)*self.horizonScrollView.width, 0) animated:YES];
    
    self.subTableView = [self currentSubTableView];
}

//移除手势
- (void)removeBehaviors {
    
    [self.animator removeAllBehaviors];
}

//获取当前页面的子tableView.
- (UIScrollView *)currentSubTableView {
    
    UIScrollView *tableView;
    //单
    switch (_currentIndex) {
        case 1:
        {
            tableView = self.productView.productTableView;
        }
            break;
        case 2:
        {
            tableView = self.evaluateView.tableView;
        }
            break;
        case 3:
        {
            tableView = self.merchantView.tableView;
        }
            break;
            
        default:
            break;
    }
    return tableView;
}


#warning 核心处理代码
#pragma mark - 手势事件 及 UIGestureRecognizerDelegate代理

/// 处理滑动手势事件
/// @param recognizer 手势
- (void)panGestureRecognizerAction:(UIPanGestureRecognizer *)recognizer {
    
    self.isStopAnimation = NO;
    
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
        {
            if (self.isVertical) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"GestureRecognizerStateBegan" object:self];
            }
            [self.animator removeAllBehaviors];
            break;
        }
        case UIGestureRecognizerStateChanged:
        {
            //locationInView:获取到的是手指点击屏幕实时的坐标点；
            //translationInView：获取到的是手指移动后，在相对坐标中的偏移量
            if (self.isVertical) {
                //往上滑为负数，往下滑为正数
                CGFloat currentY = [recognizer translationInView:self].y;
                NSLog(@"currentY....%f",currentY);
                [self controlScrollForVertical:currentY AndState:UIGestureRecognizerStateChanged];
            }
            break;
        }
        case UIGestureRecognizerStateCancelled:
        {
            break;
        }
        case UIGestureRecognizerStateEnded:
        {
            if (self.isVertical) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"GestureRecognizerStateEnded" object:self];
                if (self.contentOffset.y <= -100) {
                    
                    //向下滑动
                    if ([self.scrollDelegate respondsToSelector:@selector(ShopTabScrollViewDropDown:)]) {
                        [self.scrollDelegate ShopTabScrollViewDropDown:self];
                    }
                    
                } else {
                    
                    #warning 模拟手势结束后继续滑动的效果
                    self.dynamicItem.center = CGPointMake(0, 0);
                    //velocity是在手势结束的时候获取的竖直方向的手势速度
                    CGPoint velocity = [recognizer velocityInView:self];
                    UIDynamicItemBehavior *inertialBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.dynamicItem]];
                    [inertialBehavior addLinearVelocity:CGPointMake(0, velocity.y) forItem:self.dynamicItem];
                    // 通过尝试取2.0比较像系统的效果
                    inertialBehavior.resistance = 5.0;
                    __block CGPoint lastCenter = CGPointZero;
                    __weak typeof(self) weakSelf = self;
                    inertialBehavior.action = ^{
                        if (self.isVertical) {
                            //得到每次移动的距离
                            CGFloat currentY = weakSelf.dynamicItem.center.y - lastCenter.y;
                            [weakSelf controlScrollForVertical:currentY AndState:UIGestureRecognizerStateEnded];
                        }
                        lastCenter = weakSelf.dynamicItem.center;
                    };
                    [self.animator addBehavior:inertialBehavior];
                    self.decelerationBehavior = inertialBehavior;
                }
            }
        }
            break;
            
        default:
            break;
    }
    
    //保证每次只是移动的距离，不是从头一直移动的距离
    [recognizer setTranslation:CGPointZero inView:self];
}

//控制上下滚动的方法
- (void)controlScrollForVertical:(CGFloat)detal AndState:(UIGestureRecognizerState)state {
    
    //判断是主ScrollView滚动还是子ScrollView滚动,detal为手指移动的距离
    
    //子列表滑动
    if (self.contentOffset.y >= [MTShopSingleModel sharedInstance].maxOffsetY) {
        
        CGFloat offsetY = self.subTableView.contentOffset.y - detal;
        if (offsetY < 0) {
            //当子ScrollView的contentOffset小于0之后就不再移动子ScrollView，而要移动主ScrollView
            offsetY = 0;
            self.contentOffset = CGPointMake(self.frame.origin.x, self.contentOffset.y - detal);
        } else if (offsetY > (self.subTableView.contentSize.height - self.subTableView.frame.size.height)) {
            //当子ScrollView的contentOffset大于contentSize.height时
            offsetY = self.subTableView.contentOffset.y - rubberBandDistance(detal, self.height);
        }
        self.subTableView.contentOffset = CGPointMake(0, offsetY);
    }
    
    //当前滚动视图滑动
    else {
        
        if (self.subTableView.contentOffset.y != 0 && detal >= 0) {
            
            CGFloat offsetY = self.subTableView.contentOffset.y - detal;
            if (offsetY < 0) {
                //当子ScrollView的contentOffset小于0之后就不再移动子ScrollView，而要移动主ScrollView
                offsetY = 0;
                self.contentOffset = CGPointMake(self.frame.origin.x, self.contentOffset.y - detal);
            } else if (offsetY > (self.subTableView.contentSize.height - self.subTableView.frame.size.height)) {
                //当子ScrollView的contentOffset大于contentSize.height时
                offsetY = self.subTableView.contentOffset.y - rubberBandDistance(detal, self.height);
            }
            self.subTableView.contentOffset = CGPointMake(0, offsetY);
            
        } else {
            
            CGFloat mainOffsetY = self.contentOffset.y - detal;
            if (mainOffsetY < 0) {
                //滚到顶部之后继续往上滚动需要乘以一个小于1的系数
                mainOffsetY = self.contentOffset.y - rubberBandDistance(detal, self.height);
                
            } else if (mainOffsetY > [MTShopSingleModel sharedInstance].maxOffsetY) {
                mainOffsetY = [MTShopSingleModel sharedInstance].maxOffsetY;
            }
            self.contentOffset = CGPointMake(self.frame.origin.x, mainOffsetY);
            
            if (mainOffsetY == 0) {
                self.subTableView.contentOffset = CGPointMake(0, 0);
            }
        }
    }
    
    if (state == UIGestureRecognizerStateEnded) {
        
        #warning 模拟手势结束后继续滑动的效果
        BOOL outsideFrame = self.contentOffset.y < 0 || self.subTableView.contentOffset.y > (self.subTableView.contentSize.height - self.subTableView.frame.size.height);
        BOOL isMore = self.subTableView.contentSize.height >= self.subTableView.frame.size.height || self.contentOffset.y >= [MTShopSingleModel sharedInstance].maxOffsetY||self.contentOffset.y < 0 ;
        if (isMore && outsideFrame &&
            (self.decelerationBehavior && !self.springBehavior)) {
            CGPoint target = CGPointZero;
            BOOL isMian = NO;
            if (self.contentOffset.y < 0) {
                self.dynamicItem.center = self.contentOffset;
                target = CGPointZero;
                isMian = YES;
            } else if (self.subTableView.contentOffset.y > (self.subTableView.contentSize.height - self.subTableView.frame.size.height)) {
                self.dynamicItem.center = self.subTableView.contentOffset;

                target = CGPointMake(self.subTableView.contentOffset.x, (self.subTableView.contentSize.height - self.subTableView.frame.size.height));
                //********判断tableview的contentsize.height是否大于自身高度，从而控制滚动/
                if (self.subTableView.contentSize.height <= self.subTableView.frame.size.height) {
                    target = CGPointMake(self.subTableView.contentOffset.x,0);
                }
                isMian = NO;
            }
            [self.animator removeBehavior:self.decelerationBehavior];
            __weak typeof(self) weakSelf = self;
            UIAttachmentBehavior *springBehavior = [[UIAttachmentBehavior alloc] initWithItem:self.dynamicItem attachedToAnchor:target];
            springBehavior.length = 0;
            springBehavior.damping = 1;
            springBehavior.frequency = 2;
            springBehavior.action = ^{
                if (isMian) {
                    weakSelf.contentOffset = weakSelf.dynamicItem.center;
                    if (weakSelf.contentOffset.y == 0) {
                        self.subTableView.contentOffset = CGPointMake(0, 0);
                    }
                } else {

                    weakSelf.subTableView.contentOffset = self.dynamicItem.center;
                }
            };
            [self.animator addBehavior:springBehavior];
            self.springBehavior = springBehavior;
        }
    }
    
}

/// 手势代理 - 是否支持多个手手势共存
/// @param gestureRecognizer <#gestureRecognizer description#>
/// @param otherGestureRecognizer <#otherGestureRecognizer description#>
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        UIPanGestureRecognizer *recognizer = (UIPanGestureRecognizer *)gestureRecognizer;
        CGFloat currentY = [recognizer translationInView:self].y;
        CGFloat currentX = [recognizer translationInView:self].x;
        if (currentY == 0.0) {
            self.isVertical = NO;
            return YES;
        } else {
            ////判断如果currentX为currentY的5倍及以上就是断定为横向滑动，返回YES，否则返货NO
            if (fabs(currentX)/fabs(currentY) >= 5.0) {
                self.isVertical = NO;
                return YES;
            } else {
                self.isVertical = YES;
                return NO;
            }
        }
    }
    return NO;
}

#pragma mark - UIScrollView delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self) {
        
        //如果已经回到顶部了，则移除手势，禁止来回谈动
        if (self.contentOffset.y == 0) {
            [self removeBehaviors];
        }
        
        if (!self.isStopAnimation) {
            if ([self.scrollDelegate respondsToSelector:@selector(ShopTabScrollViewDidScroll:)]) {
                [self.scrollDelegate ShopTabScrollViewDidScroll:scrollView];
            }
        }
        
        //设置二级联动的左tableview的偏移量
        if (self.productView) {
            [self.productView superScrollViewDidScrollOffset:scrollView.contentOffset.y];
        }
        
    } else if (scrollView == self.horizonScrollView ) {
    
        CGFloat scorllOffsetW = self.horizonScrollView.width*2;
        CGFloat currentOffsetX =  self.horizonScrollView.contentOffset.x;
        CGFloat rate = currentOffsetX/scorllOffsetW;//速率
        CGFloat offset_X = self.width/3 * rate*2;
        self.menuLine.x = offset_X+(self.width/3/2-10);
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView == self.horizonScrollView) {
        
        NSInteger index = self.horizonScrollView.contentOffset.x/self.horizonScrollView.frame.size.width;
        _currentIndex = index+1;
        UIButton *lastBT = (UIButton *)[_menuView viewWithTag:_lastIndex];
        UIButton *currentBT = (UIButton *)[_menuView viewWithTag:_currentIndex];
        [lastBT setTitleColor:kColorLightGray forState:UIControlStateNormal];
        [currentBT setTitleColor:kColorBlack forState:UIControlStateNormal];
        _lastIndex = _currentIndex;
        self.subTableView = [self currentSubTableView];
    }
}

#pragma mark - 懒加载
- (UIScrollView *)horizonScrollView {
    if (_horizonScrollView == nil) {
        _horizonScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.menuView.bottom, self.width, self.height-_menuView.bottom+ [MTShopSingleModel sharedInstance].maxOffsetY)];
        _horizonScrollView.contentSize = CGSizeMake(self.width * 3, _horizonScrollView.height);
        _horizonScrollView.pagingEnabled = YES;
        _horizonScrollView.scrollEnabled = YES;
        _horizonScrollView.showsHorizontalScrollIndicator = NO;
        _horizonScrollView.backgroundColor = kColorBgColor;
        _horizonScrollView.delegate = self;
    }
    return _horizonScrollView;
}

- (PartProductView *)productView {
    if (!_productView) {
        _productView = [[PartProductView alloc]initWithFrame:CGRectMake(0, 0, self.width, _horizonScrollView.height)];
        _productView.shopSuperView = self;
    }
    return _productView;
}

- (PartEvaluateView *)evaluateView {
    if (!_evaluateView) {
        _evaluateView = [[PartEvaluateView alloc]initWithFrame:CGRectMake(self.width, 0, self.width, _horizonScrollView.height)];
    }
    return _evaluateView;
}

- (PartMerchantView *)merchantView {
    if (!_merchantView) {
        _merchantView = [[PartMerchantView alloc]initWithFrame:CGRectMake(self.width*2, 0, self.width, _horizonScrollView.height)];
    }
    return _merchantView;
}

@end
